package com.ray.common.config.shiro;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    /**
     * 过滤器工厂
     * @Qualifier("securityManager") 将securityManager从spring中取出
     * （“shiroFilterFactoryBean”）可加可不加
     */
    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);
        //权限设置
        Map<String,String> filtermap = new LinkedHashMap<>();
        /**
         * 去登录可访问
         */
        filtermap.put("/toLogin", "anon");
        filtermap.put("/sys/user/login", "anon");
        filtermap.put("/sys/user/userList", "anon");
        /**
         * 静态资源可访问
         */
        filtermap.put("/css/**", "anon");
        filtermap.put("/layui/**", "anon");
        filtermap.put("/js/**", "anon");
        filtermap.put("/images/**", "anon");
        filtermap.put("*.png", "anon");
        filtermap.put("*jpg", "anon");

        //未认证都不允许通过
        filtermap.put("/**", "authc");
        factoryBean.setFilterChainDefinitionMap(filtermap);
        //设置登录页面
        factoryBean.setLoginUrl("/toLogin");
        //设置未授权页面
        factoryBean.setUnauthorizedUrl("/sys/user/unauth");
        return factoryBean;
    }

    /**
     * 安全管理器
     * @Qualifier("accountRealm") 将AccountRealm从spring中取出
     *
     */
    @Bean("securityManager")
    public DefaultWebSecurityManager securityManager(@Qualifier("myRealm") MyRealm myRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myRealm);
        return securityManager;
    }

    /**
     * @Bean 将AccountRealm放入spring容器
     */
    @Bean("myRealm")
    public MyRealm myRealm(){
        return new MyRealm();
    }






}
